package com.zhijian.medical.controller;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.zhijian.medical.entity.vo.request.*;
import com.zhijian.medical.entity.vo.response.RoutinePatientRegistVo;
import com.zhijian.medical.entity.vo.response.RoutinePatientVo;
import com.zhijian.medical.enums.PatientEnums;
import com.zhijian.medical.enums.RoutinePathologySampleStepEnum;
import com.zhijian.medical.service.RoutinePatientRegistService;
import com.zhijian.medical.service.RoutinePatientService;
import com.zhijian.medical.service.RoutineSampleService;
import com.zhijian.response.annotation.Response;
import com.zhijian.util.page.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 常规病理-病人 控制层
 *
 * @author auto
 * @version 1.0
 * @date 2024-06-26 15:42:40
 */
@Slf4j
@Controller
@Api(tags = "常规病理-病人")
public class RoutinePatientController {

    @Autowired
    private RoutinePatientService service;

    @Autowired
    private RoutineSampleService routineSampleService;

    @Autowired
    private RoutinePatientRegistService registService;

    /**
     * 离体
     *
     * @param param
     * @return
     */
    @Response
    @PostMapping("/routine/off/body")
    @ApiOperation("离体")
    public boolean offBody(@RequestBody RoutineOffBodyVo param) {
        log.info("{} - {}| insert info", this.getClass().getSimpleName(), param);
        return service.offBody(param);
    }

    /**
     * 固定
     *
     * @param param
     * @return
     */
    @Response
    @PutMapping("/routine/off/fixed")
    @ApiOperation("固定")
    public boolean fixed(@RequestBody List<RoutineSampleFixedVo> param) {
        log.info("{} - {}| insert info", this.getClass().getSimpleName(), param);
        return service.fixed(param);
    }

    /**
     * 登记
     *
     * @param param
     * @return
     */
    @Response
    @PutMapping("/routine/off/register")
    @ApiOperation("登记")
    public boolean register(@RequestBody List<RoutineSampleRegisterVo> param) {
        log.info("{} - {}| insert info", this.getClass().getSimpleName(), param);
        return true;//service.register(param);
    }

    @Response
    @PostMapping("/routine/off/register/{patientId}")
    @ApiOperation("登记--旧")
    public boolean register(@PathVariable("patientId") Long patientId) {
        log.info("{} - {}| insert info", this.getClass().getSimpleName(), patientId);
        return service.register(patientId);
    }

    @Response
    @PostMapping("/routine/off/register/new")
    @ApiOperation("登记--新")
    public boolean registerNew(@RequestBody RoutinePatientRegistSaveOrUpdateVo param) {
        log.info("{} - {}| insert info", this.getClass().getSimpleName(), param);
        return service.registerNew(param);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Response
    @DeleteMapping("/routine/patient/{id}")
    @ApiOperation("删除")
    public boolean delete(@PathVariable("id") Long id) {
        log.info("{} - {}| delete info", this.getClass().getSimpleName(), id);
        service.deleteById(id);
        return true;
    }

//    /**
//     * 修改
//     *
//     * @param id
//     * @param param
//     * @return
//     */
//    @Response
//    @PutMapping("/routine/patient/{id}")
//    @ApiOperation("修改")
//    public boolean update(@PathVariable("id") Long id, @RequestBody RoutinePatientSaveOrUpdateVo param) {
//        log.info("{} - {}| update info, {}", this.getClass().getSimpleName(), id, param);
//        param.setId(id);
//        return service.modify(param);
//    }

    /**
     * 根据id查询病人详情，包含样本列表
     *
     * @param id
     * @return
     */
    @Response
    @GetMapping("/routine/patient/{id}")
    @ApiOperation("根据id查询病人详情，包含样本列表 -- 旧")
    public RoutinePatientVo selectById(@PathVariable("id") Long id) {
        log.info("{} - {}| query info", this.getClass().getSimpleName(), id);
        return service.selectVoById(id);
    }

    @Response
    @GetMapping("/routine/patient")
    @ApiOperation("根据id查询病人详情，包含样本列表 -- 新")
    public RoutinePatientVo selectByIdNew(@RequestParam("id") Long id, Byte type) {
        log.info("{} - {}| query info", this.getClass().getSimpleName(), id);
        return service.selectVoByIdNew(id, type);
    }


    @Response
    @PutMapping("/routine/sample/batch/upd")
    @ApiOperation("固定-批量修改样本值")
    public void batchUpdSample(@RequestBody List<RoutineSampleSaveOrUpdateVo.BatchUpdateFixedData> batchUpdateFixedDataList) {
        log.info("{} - {}| query info", this.getClass().getSimpleName(), batchUpdateFixedDataList);
        routineSampleService.batchUpd(batchUpdateFixedDataList);
    }

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @Response
    @PostMapping("/routine/patient/page")
    @ApiOperation("分页查询")
    public Page<RoutinePatientVo> selectByCondition(@RequestBody(required = false) RoutinePatientSearchVo param) {
        if (param == null)
            param = RoutinePatientSearchVo.builder().build();
        log.info("{} - {}| query info", this.getClass().getSimpleName(), param);
        return service.selectPage(param);
    }

    @Response
    @PostMapping("/routine/patient/page/body")
    @ApiOperation("离体分页查询")
    public Page<RoutinePatientVo> selectOffBodyByCondition(@RequestBody(required = false) RoutinePatientSearchVo param) {
        if (param == null)
            param = RoutinePatientSearchVo.builder().build();
        log.info("{} - {}| query info", this.getClass().getSimpleName(), param);
        stateQueryHandle(param, RoutinePathologySampleStepEnum.LT);
        param.setPatientHandleType(PatientEnums.PatientHandleTypeEnum.NORMAL_HANDLE.getCode());
        Page<RoutinePatientVo> patientVoPage = service.selectPage(param);
        stateHandle(patientVoPage.getData(), RoutinePathologySampleStepEnum.LT);
        return patientVoPage;
    }

    @Response
    @PostMapping("/routine/patient/page/fixed")
    @ApiOperation("固定分页查询")
    public Page<RoutinePatientVo> selectFixedByCondition(@RequestBody(required = false) RoutinePatientSearchVo param) {
        if (param == null)
            param = RoutinePatientSearchVo.builder().build();
        log.info("{} - {}| query info", this.getClass().getSimpleName(), param);
        if (CollUtil.isNotEmpty(param.getPatientStateList())) {
            List<Integer> integers = fixQueryHandle(param.getPatientStateList(), RoutinePathologySampleStepEnum.GD);
            param.setPatientStateList(integers);
        } else {
            stateQueryHandle(param, RoutinePathologySampleStepEnum.GD);
        }
        param.setPatientHandleType(PatientEnums.PatientHandleTypeEnum.NORMAL_HANDLE.getCode());
        Page<RoutinePatientVo> patientVoPage = service.selectPage(param);
        stateHandle(patientVoPage.getData(), RoutinePathologySampleStepEnum.GD);
        return patientVoPage;
    }

    @Response
    @PostMapping("/routine/patient/page/register")
    @ApiOperation("登记分页查询")
    public Page<RoutinePatientVo> selectRegisterByCondition(@RequestBody(required = false) RoutinePatientSearchVo param) {
        if (param == null)
            param = RoutinePatientSearchVo.builder().build();
        log.info("{} - {}| query info", this.getClass().getSimpleName(), param);
        stateQueryHandle(param, RoutinePathologySampleStepEnum.DJ);
        param.setPatientHandleType(PatientEnums.PatientHandleTypeEnum.NORMAL_HANDLE.getCode());
        param.setRegisterStateCondition(3);
        Page<RoutinePatientVo> patientVoPage = service.selectPage(param);
        stateHandle(patientVoPage.getData(), RoutinePathologySampleStepEnum.DJ);
        return patientVoPage;
    }

    /**
     * 列表查询
     *
     * @param param
     * @return
     */
    @Response
    @PostMapping("/routine/patient/list")
    @ApiOperation("列表查询")
    public List<RoutinePatientVo> selectList(@RequestBody(required = false) RoutinePatientSearchVo param) {
        if (param == null)
            param = RoutinePatientSearchVo.builder().build();
        log.info("{} - {}| query info", this.getClass().getSimpleName(), param);
        return service.selectList(param);
    }

    private void stateHandle(List<RoutinePatientVo> list, RoutinePathologySampleStepEnum routinePathologySampleStepEnum){
        PatientEnums.PatientStateEnum[] values = PatientEnums.PatientStateEnum.values();
        for (RoutinePatientVo routinePatientVo : list){
            //离体模块
            if (RoutinePathologySampleStepEnum.LT.getCode().byteValue() == routinePathologySampleStepEnum.getCode().byteValue()){
                if (routinePatientVo.getState() > PatientEnums.PatientStateEnum.OFF_BODY.getCode()){
                    routinePatientVo.setStateStr(PatientEnums.PatientStateEnum.OFF_BODY.getDesc());
                }else {
                    routinePatientVo.setStateStr(values[routinePatientVo.getState()].getDesc());
                }
                //固定模块
            }else if (RoutinePathologySampleStepEnum.GD.getCode().byteValue() == routinePathologySampleStepEnum.getCode().byteValue()){
                //未处理
                if (PatientEnums.PatientStateEnum.OFF_BODY.getCode().equals(routinePatientVo.getState())){
                    routinePatientVo.setStateStr(PatientEnums.PatientStateEnum.GD_NO_DONE.getDesc());
                    //均为已处理
                }else if (routinePatientVo.getState() > PatientEnums.PatientStateEnum.GD_DONE.getCode()){
                    routinePatientVo.setStateStr(PatientEnums.PatientStateEnum.GD_DONE.getDesc());
                }else {
                    routinePatientVo.setStateStr(values[routinePatientVo.getState()].getDesc());
                }
            }else {
                if (!PatientEnums.PatientStateEnum.OFF_BODY_EXCEPTION.getCode().equals(routinePatientVo.getState())
                        && !PatientEnums.PatientStateEnum.GD_EXCEPTION.getCode().equals(routinePatientVo.getState()) ){
                    routinePatientVo.setStateStr(PatientEnums.PatientStateEnum.REGISTER.getDesc());
                }else {
                    routinePatientVo.setStateStr(values[routinePatientVo.getState()].getDesc());
                }
            }
        }
    }

    private void stateQueryHandle(RoutinePatientSearchVo param, RoutinePathologySampleStepEnum routinePathologySampleStepEnum){
        //状态处理
        if (param.getPatientState() != null){
            if (RoutinePathologySampleStepEnum.LT.getCode().byteValue() == routinePathologySampleStepEnum.getCode().byteValue()){
                //正常与离体异常的查询
                if (param.getPatientState().equals(PatientEnums.PatientStateEnum.OFF_BODY.getCode())){
                    param.setPatientStateList(Lists.newArrayList(1, 2, 3, 4, 5));
                }else {
                    param.setPatientStateList(Lists.newArrayList(0));
                }
            }else if (RoutinePathologySampleStepEnum.GD.getCode().byteValue() == routinePathologySampleStepEnum.getCode().byteValue()){
                //已处理。未处理，固定异常的查询
                if (param.getPatientState().equals(PatientEnums.PatientStateEnum.GD_NO_DONE.getCode())){
                    param.setPatientStateList(Lists.newArrayList(1));
                }else if (param.getPatientState().equals(PatientEnums.PatientStateEnum.GD_DONE.getCode())){
                    param.setPatientStateList(Lists.newArrayList(4,5));
                }else if (param.getPatientState().equals(PatientEnums.PatientStateEnum.OFF_BODY_EXCEPTION.getCode())){
                    param.setPatientStateList(Lists.newArrayList(0));
                }else {
                    param.setPatientStateList(Lists.newArrayList(3));
                }
            }else {
                //正常与固定异常查询
                if (param.getPatientState().equals(PatientEnums.PatientStateEnum.REGISTER.getCode())){
                    param.setPatientStateList(Lists.newArrayList(1, 2, 4, 5));
                }else {
                    param.setPatientStateList(Lists.newArrayList(3));
                }
            }
        }
    }


    private List<Integer> fixQueryHandle(List<Integer> patientStateList, RoutinePathologySampleStepEnum routinePathologySampleStepEnum){
        //状态处理
        Set<Integer> patientStateSet = new HashSet<Integer>();
        for (Integer patientState : patientStateList){
            if (patientState != null){
                if (RoutinePathologySampleStepEnum.LT.getCode().byteValue() == routinePathologySampleStepEnum.getCode().byteValue()){
                    //正常与离体异常的查询
                    if (patientState.equals(PatientEnums.PatientStateEnum.OFF_BODY.getCode())){
                        patientStateSet.addAll(Lists.newArrayList(1, 2, 3, 4, 5));
                    }else {
                        patientStateSet.addAll(Lists.newArrayList(0));
                    }
                }else if (RoutinePathologySampleStepEnum.GD.getCode().byteValue() == routinePathologySampleStepEnum.getCode().byteValue()){
                    //已处理。未处理，固定异常的查询
                    if (patientState.equals(PatientEnums.PatientStateEnum.GD_NO_DONE.getCode())){
                        patientStateSet.addAll(Lists.newArrayList(1));
                    }else if (patientState.equals(PatientEnums.PatientStateEnum.GD_DONE.getCode())){
                        patientStateSet.addAll(Lists.newArrayList(4,5));
                    }else if (patientState.equals(PatientEnums.PatientStateEnum.OFF_BODY_EXCEPTION.getCode())){
                        patientStateSet.addAll(Lists.newArrayList(0));
                    }else {
                        patientStateSet.addAll(Lists.newArrayList(3));
                    }
                }else {
                    //正常与固定异常查询
                    if (patientState.equals(PatientEnums.PatientStateEnum.REGISTER.getCode())){
                        patientStateSet.addAll(Lists.newArrayList(1, 2, 4, 5));
                    }else {
                        patientStateSet.addAll(Lists.newArrayList(3));
                    }
                }
            }
        }
        return new ArrayList<Integer>(patientStateSet);
    }

    @Response
    @GetMapping("/routine/patient/his/{hisNum}/{type}")
    @ApiOperation("根据his识别号查询, type:1-住院号；2-病理号；3-门诊号")
    public RoutinePatientRegistVo selectByHisId(@PathVariable("hisNum") String hisNum, @PathVariable("type") Integer type) {
        log.info("{} - {}| query info", this.getClass().getSimpleName(), hisNum);
        return registService.selectByHisId(hisNum, type);
    }
}